package com.example.schoolexam2.service.impl;

import com.example.schoolexam2.entity.QuestionCheckd;
import com.example.schoolexam2.entity.QuestionFill;
import com.example.schoolexam2.entity.QuestionJudge;
import com.example.schoolexam2.entity.QuestionRadio;
import com.example.schoolexam2.mapper.EmplMapper;
import com.example.schoolexam2.mapper.PowerMapper;
import com.example.schoolexam2.mapper.QuestionMapper;
import com.example.schoolexam2.service.QuestionService;
import com.example.schoolexam2.utils.PageUtils;
import com.example.schoolexam2.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

import static com.example.schoolexam2.utils.QuestionAboutUtil.*;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    QuestionMapper questionMapper;
    @Autowired
    EmplMapper emplMapper;
    @Autowired
    PowerMapper powerMapper;
    PageUtils pageUtils = new PageUtils();
    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 读取题库文件，得到试题并保存到数据库中
     * 得到文件地址，通过pio逐行读取
     */
    //暂时定义题文件中图片保存位置
    public static String IMgFolder = "imgs/";
    public static String IMgInternet = "Http://192.168.1.105:8898/api/imgs";

    /**
     * 读取试题文件并保存
     *
     * @param file
     * @param i
     * @return
     * @throws Exception
     */
    @Override
    public boolean redAndSave(MultipartFile file, int i, String teacherId) throws Exception {  //参数为1代表是xlsx文件
        String departmentId = emplMapper.findDepartmentByEmplyee(teacherId);
        if (i == 1) {
            XSSFWorkbook sheets = new XSSFWorkbook(file.getInputStream());  //将文件源换成前端传输的文件源
//            XSSFWorkbook sheets = new XSSFWorkbook(new FileInputStream("C:/Users/AWei/Desktop/Test.xlsx"));
            XSSFSheet sheet = sheets.getSheetAt(0);

            //先获取所有的图片资源位置 图片位置坐标1-1，图片地址
            Map<String, String> allPicture = findAllPicture(sheet);
            String[][] pics = zhongjian(allPicture);

            //获取最后一行的num，循环从第一行开始 此处从0开始
            int lastRowNum = sheet.getLastRowNum();

            //防止性能浪费，在读取完试题后再保存，当中出现错误就不保存
            List<QuestionRadio> radios = new ArrayList<>();
            List<QuestionCheckd> checkds = new ArrayList<>();
            List<QuestionFill> fills = new ArrayList<>();
            List<QuestionJudge> judges = new ArrayList<>();
            try {
                for (int row = 1; row <= lastRowNum; row++) {
                    //获取头行数据，判断题目类型
                    XSSFCell cell = sheet.getRow(row).getCell(0);
                    cell.setCellType(CellType.STRING);
                    String type = cell.getStringCellValue();
                    completePacking(sheet, type, row, pics, radios, checkds, fills, judges, departmentId);
                }
                for (QuestionJudge judge : judges) {
                    judge.setTeacherId(teacherId);
                    questionMapper.saveJudge(judge);
                }
                for (QuestionFill fill : fills) {
                    fill.setTeacherId(teacherId);
                    questionMapper.saveFill(fill);
                }
                for (QuestionCheckd checkd : checkds) {
                    checkd.setTeacherId(teacherId);
                    questionMapper.saveCheck(checkd);
                }
                for (QuestionRadio radio : radios) {
                    radio.setTeacherId(teacherId);
                    questionMapper.saveRadio(radio);
                }
                logger.info("保存成功");
                return true;
            } catch (NullPointerException e) {
                //当前列表关键字段有空值
                logger.info("保存失败");
                return false;
            }
        } //解析xlsx文件
        return xlx(file, teacherId, departmentId); //解析xls文件
    }

    //对xls文件的解析
    private boolean xlx(MultipartFile file, String teacherId, String departmentId) throws Exception {
        HSSFWorkbook sheets = new HSSFWorkbook(file.getInputStream());  //将文件源换成前端传输的文件源
//        HSSFWorkbook sheets = new HSSFWorkbook(new FileInputStream("C:/Users/AWei/Desktop/Test.xls"));
        HSSFSheet sheet = sheets.getSheetAt(0);

        //先获取所有的图片资源位置 图片位置坐标1-1，图片地址
        Map<String, String> allPicture = findAllPicture(sheet);
        String[][] pics = zhongjian(allPicture);

        //获取最后一行的num，循环从第一行开始 此处从0开始
        int lastRowNum = sheet.getLastRowNum();

        //防止性能浪费，在读取完试题后再保存，当中出现错误就不保存
        List<QuestionRadio> radios = new ArrayList<>();
        List<QuestionCheckd> checkds = new ArrayList<>();
        List<QuestionFill> fills = new ArrayList<>();
        List<QuestionJudge> judges = new ArrayList<>();
        try {
            for (int row = 1; row <= lastRowNum; row++) {
                //获取头行数据，判断题目类型
                HSSFCell cell = sheet.getRow(row).getCell(0);
                cell.setCellType(CellType.STRING);
                String type = cell.getStringCellValue();
                completePacking(sheet, type, row, pics, radios, checkds, fills, judges, departmentId);
            }
            for (QuestionJudge judge : judges) {
                judge.setTeacherId(teacherId);
                questionMapper.saveJudge(judge);
            }
            for (QuestionFill fill : fills) {
                fill.setTeacherId(teacherId);
                questionMapper.saveFill(fill);
            }
            for (QuestionCheckd checkd : checkds) {
                checkd.setTeacherId(teacherId);
                questionMapper.saveCheck(checkd);
            }
            for (QuestionRadio radio : radios) {
                radio.setTeacherId(teacherId);
                questionMapper.saveRadio(radio);
            }
            logger.info("保存成功");
            return true;
        } catch (NullPointerException e) {
            //当前列表关键字段有空值
            logger.info("保存失败");
            return false;
        }

    }


    /**
     * 查询所有的试题
     *
     * @return
     */
    @Override
    public QuestionsToListVo getAllQuestion(String[] department, String isPublic) {
        List<QuestionRadio> allRadio = questionMapper.findAllRadio(department, isPublic,-1,-1,null);
        List<QuestionCheckd> allCheckd = questionMapper.findAllCheckd(department, isPublic,-1,-1,null);
        List<QuestionFill> allFill = questionMapper.findAllFill(department, isPublic,-1,-1,null);
        List<QuestionJudge> allJudge = questionMapper.findAllJudge(department, isPublic,-1,-1,null);
        return new QuestionsToListVo(allRadio, allCheckd, allFill, allJudge);
//        return null;
    }

    /**
     * 通过试题id删除试题，如果试题被选择到试卷中就删除失败
     *
     * @param questionId
     * @return
     */
    @Override
    public Boolean delQuestion(String questionId, int type) {
        int resultNum;
        switch (type) {
            case 1:  //单选
                resultNum = questionMapper.delQuestionRadio(questionId);
                if (resultNum <= 0) {
                    //如果resultNum！>0,该试题被选中，要将其isShow值变成0
                    questionMapper.changeShowRadio(questionId);
                }
                return true;
            case 2:
                resultNum = questionMapper.delQuestionCheckd(questionId);
                if (resultNum <= 0) {
                    //如果resultNum！>0,该试题被选中，要将其isShow值变成0
                    questionMapper.changeShowCheckd(questionId);
                }
                return true;
            case 3:
                resultNum = questionMapper.delQuestionFill(questionId);
                if (resultNum <= 0) {
                    //如果resultNum！>0,该试题被选中，要将其isShow值变成0
                    questionMapper.changeShowFill(questionId);
                }
                return true;
            case 4:
                resultNum = questionMapper.delQuestionJudge(questionId);
                if (resultNum <= 0) {
                    //如果resultNum！>0,该试题被选中，要将其isShow值变成0
                    questionMapper.changeShowJudge(questionId);
                }
                return true;
            default:
                return false;
        }

    }

    /**
     * 更新试题
     */
    @Override
    public Boolean updateQuestion(Object obj) {
        if (obj instanceof QuestionRadio) {
            questionMapper.updateRadio((QuestionRadio) obj);
        } else if (obj instanceof QuestionCheckd) {
            questionMapper.updateCheckd((QuestionCheckd) obj);
        } else if (obj instanceof QuestionFill) {
            questionMapper.updateFill((QuestionFill) obj);
        } else if (obj instanceof QuestionJudge) {
            questionMapper.updateJudge((QuestionJudge) obj);
        } else {
            return false;
        }
        return true;
    }

    /**
     * 通过试题id获取试题
     */
    @Override
    public Object getQuestionById(String questionId, String type) {
        switch (type) {
            case "1":
                return questionMapper.findRadioById(questionId);
            case "2":
                return questionMapper.findCheckdById(questionId);
            case "3":
                return questionMapper.findFillById(questionId);
            case "4":
                return questionMapper.findJudgeById(questionId);
        }
        return null;
    }

    /**
     * 下面四个方法用于查询分页的试题数据
     *
     * @param department  待查部门数组
     * @param isPublic    是否公开
     * @param currentpage 当前页
     * @param size        页面长度
     * @return
     */
    @Override
    public PageVo getPageRadio(String[] department, String isPublic, int currentpage, int size,String qname) {
        int judgeCount = questionMapper.findRadioCount(department,isPublic,qname);
        PageVo pageVo = pageUtils.page(judgeCount, currentpage, size);
        pageVo.setData(Collections.singletonList(questionMapper.findAllRadio(department, isPublic, pageVo.getStartCount(), pageVo.getSize(),qname)));
        return pageVo;
    }

    @Override
    public PageVo getPageCheckd(String[] department, String isPublic, int currentpage, int size,String qname) {
        int checkdCount = questionMapper.findCheckdCount(department,isPublic,qname);
        PageVo pageVo = pageUtils.page(checkdCount, currentpage, size);
        pageVo.setData(Collections.singletonList(questionMapper.findAllCheckd(department, isPublic, pageVo.getStartCount(), pageVo.getSize(),qname)));
        System.out.println(pageVo);
        return pageVo;
    }

    @Override
    public PageVo getPageFill(String[] department, String isPublic, int currentpage, int size,String qname) {
        int fillCount = questionMapper.findFillCount(department,isPublic,qname);
        PageVo pageVo = pageUtils.page(fillCount, currentpage, size);
        pageVo.setData(Collections.singletonList(questionMapper.findAllFill(department, isPublic, pageVo.getStartCount(), pageVo.getSize(),qname)));
        System.out.println(pageVo);
        return pageVo;
    }

    @Override
    public PageVo getPageJudge(String[] department, String isPublic, int currentpage, int size,String qname) {
        int judgeCount = questionMapper.findJudgeCount(department,isPublic,qname);
        PageVo pageVo = pageUtils.page(judgeCount, currentpage, size);
        pageVo.setData(Collections.singletonList(questionMapper.findAllJudge(department, isPublic, pageVo.getStartCount(), pageVo.getSize(),qname)));
        return pageVo;
    }

    @Override
    public int getQuestionCount(String type) {
        switch (type) {
            case "1":
                return questionMapper.findRadioCount(null,null,null);
            case "2":
                return questionMapper.findCheckdCount(null,null,null);
            case "3":
                return questionMapper.findFillCount(null,null,null);
            case "4":
                return questionMapper.findJudgeCount(null,null,null);
        }
        return 0;
    }
}
